import { Op } from 'sequelize'
import Post, { type PostAttributes, type PostCreationAttributes } from '../models/Post'
import User from '../models/User'

export class PostService {
  // 获取帖子列表
  static async getPosts(page: number = 1, pageSize: number = 10, search?: string) {
    const offset = (page - 1) * pageSize
    const where: any = {}

    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { content: { [Op.like]: `%${search}%` } }
      ]
    }

    const { count, rows } = await Post.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'name']
        }
      ],
      order: [
        ['isPinned', 'DESC'],
        ['createdAt', 'DESC']
      ],
      limit: pageSize,
      offset
    })

    return {
      posts: rows,
      total: count,
      page,
      pageSize
    }
  }

  // 获取帖子详情
  static async getPostById(id: number) {
    const post = await Post.findByPk(id, {
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'name']
        }
      ]
    })

    if (post) {
      // 增加浏览次数
      await post.increment('viewCount')
    }

    return post
  }

  // 创建帖子
  static async createPost(postData: PostCreationAttributes) {
    const post = await Post.create(postData)
    
    // 更新用户的发帖数量
    await User.increment('commits_post', {
      where: { id: postData.authorId }
    })

    return post
  }

  // 更新帖子
  static async updatePost(id: number, postData: Partial<PostAttributes>) {
    const [affectedCount] = await Post.update(postData, {
      where: { id }
    })
    return affectedCount > 0
  }

  // 删除帖子
  static async deletePost(id: number) {
    const affectedCount = await Post.destroy({
      where: { id }
    })
    return affectedCount > 0
  }

  // 点赞帖子
  static async likePost(id: number) {
    const post = await Post.findByPk(id)
    if (post) {
      await post.increment('likeCount')
      return true
    }
    return false
  }

  // 取消点赞帖子
  static async unlikePost(id: number) {
    const post = await Post.findByPk(id)
    if (post && post.likeCount > 0) {
      await post.decrement('likeCount')
      return true
    }
    return false
  }

  // 置顶帖子
  static async pinPost(id: number) {
    const [affectedCount] = await Post.update(
      { isPinned: true },
      { where: { id } }
    )
    return affectedCount > 0
  }

  // 取消置顶帖子
  static async unpinPost(id: number) {
    const [affectedCount] = await Post.update(
      { isPinned: false },
      { where: { id } }
    )
    return affectedCount > 0
  }

  // 增加浏览次数
  static async incrementViewCount(id: number) {
    await Post.increment('viewCount', {
      where: { id }
    })
  }
}
